<template>
  <el-dialog
    title="新增任务"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="1000px"
    v-dialog-drag
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      :disabled="disabled || !canEdit"
      v-loading="loading"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="所属工厂" prop="ownedFactory">
            <el-select v-model="form.ownedFactory" placeholder="请选择所属工厂">
              <el-option
                v-for="item in factoryList"
                :key="item.factoryDeptCode"
                :label="item.factoryName"
                :value="item.factoryDeptCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="执行时间" prop="actualExecuteStartTime">
            <el-date-picker
              v-model="form.actualExecuteStartTime"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
            <span style="margin: 0 10px">至</span>
            <el-date-picker
              v-model="form.actualExecuteEndTime"
              type="datetime"
              placeholder="请选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="!!form.ownedFactory" :gutter="10">
        <el-col :span="24">
          <el-form-item
            label="选择任务配置"
            prop="taskConfigInfoList"
            class="task-config-list"
          >
            <span></span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="!!form.ownedFactory" :gutter="10">
        <el-col :span="24">
          <div class="search-bar">
            <el-select
              v-model="taskTypeSearchKey"
              placeholder="请选择任务类型"
              clearable
              size="small"
              class="w200"
            >
              <el-option
                v-for="item in dict.taskType"
                :key="item.codevalue"
                :label="item.codename"
                :value="item.codevalue"
              >
              </el-option>
            </el-select>
            <el-input
              v-model="taskConfigNameSearchKey"
              class="w200"
              placeholder="请输入任务配置名称"
              size="small"
              clearable
            ></el-input>
            <el-button type="primary" size="small" @click="handleSearch"
              >查询</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-row v-show="!!form.ownedFactory" :gutter="10">
        <el-col :span="24">
          <el-table
            ref="table"
            :data="taskConfigurationList"
            tooltip-effect="dark"
            style="width: 100%"
            stripe
            border
            height="325px"
            v-loading="tableLoading"
          >
            <el-table-column
              type="selection"
              width="60"
              align="center"
            ></el-table-column>
            <el-table-column
              label="任务配置名称"
              prop="taskName"
              width="150"
            ></el-table-column>
            <el-table-column label="任务类型" prop="taskType" width="120">
              <template slot-scope="{ row }">
                {{ taskTypeOptionsMap[row.taskType] }}
              </template>
            </el-table-column>
            <el-table-column label="任务性质" prop="taskNature" width="100">
              <template slot-scope="{ row }">
                {{ taskNatureOptionsMap[row.taskNature] }}
              </template>
            </el-table-column>
            <el-table-column label="任务执行人" min-width="200" @click.stop>
              <template slot-scope="{ row }">
                <!-- 执行人选择的是部门的，显示执行部门 -->
                <OrganizationSelect
                  v-if="row.operatorType == 'dept'"
                  v-model="row.executiveAgency"
                  placeholder="部门"
                  class="executive-agency"
                  :clearable="false"
                  @click.native.stop
                  @change="handleOperatorChange(row, 'executiveAgency', $event)"
                ></OrganizationSelect>
                <!-- 非部门的，显示车间-产线-工位/岗位 -->
                <div v-else class="in-row" @click.stop>
                  <el-select
                    v-model="row.ownedWorkshop"
                    placeholder="车间"
                    @click.stop
                    @change="handleOperatorChange(row, 'ownedWorkshop', $event)"
                  >
                    <el-option
                      v-for="item in getWorkshopOptions(row.ownedFactory)"
                      :key="item.workshopCode"
                      :label="item.workshopName"
                      :value="item.workshopCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="row.ownedProductionLine"
                    placeholder="产线"
                    @click.stop
                    @change="
                      handleOperatorChange(row, 'ownedProductionLine', $event)
                    "
                  >
                    <el-option
                      v-for="item in getProductionLineOptions(
                        row.ownedWorkshop
                      )"
                      :key="item.lineCode"
                      :label="item.lineName"
                      :value="item.lineCode"
                    >
                    </el-option>
                  </el-select>
                  <!-- 工位 -->
                  <el-select
                    v-if="row.operatorType == 'station'"
                    v-model="row.operator"
                    placeholder="工位"
                    @click.stop
                    @change="handleOperatorChange(row, 'operator', $event)"
                  >
                    <el-option
                      v-for="item in getStationOptions(row.ownedProductionLine)"
                      :key="item.workStationCode"
                      :label="item.workStationName"
                      :value="item.workStationCode"
                    >
                    </el-option>
                  </el-select>
                  <!-- 岗位 -->
                  <el-select
                    v-if="row.operatorType == 'job'"
                    v-model="row.operator"
                    placeholder="岗位"
                    @click.stop
                    @change="handleOperatorChange(row, 'operator', $event)"
                  >
                    <el-option
                      v-for="item in dict.PostManage"
                      :key="item.codevalue"
                      :label="item.codename"
                      :value="item.codevalue"
                    >
                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="pager.total"
            :page.sync="pager.pageNum"
            :limit.sync="pager.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        v-if="canEdit"
        type="primary"
        :loading="saveloading"
        @click="handleSubmit"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import { checkPermi } from "@/utils/permission";
import WorkTree from "@/utils/workTree";
import { saveTask } from "@/api/taskMgmt/center";
import { getTaskConfigList } from "@/api/taskMgmt/configuration";
import OrganizationSelect from "@/views/components/organizationSelect";
export default {
  components: { OrganizationSelect },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["taskType", "taskNature", "PostManage"],
  data() {
    return {
      loading: false,
      form: {
        ownedFactory: null,
        actualExecuteStartTime: null,
        actualExecuteEndTime: null,
        taskConfigInfoList: [],
      },
      rules: {
        ownedFactory: [
          { required: true, message: "请选择所属工厂", trigger: "change" },
        ],
        actualExecuteStartTime: [
          { required: true, message: "请选择执行时间", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!value || !this.form.actualExecuteEndTime) {
                callback(new Error("请选择执行时间"));
                return;
              } else if (
                new Date(value).getTime() >
                new Date(this.form.actualExecuteEndTime).getTime()
              ) {
                callback(new Error("开始时间不能大于结束时间"));
                return;
              }
              callback();
            },
          },
        ],
        taskConfigInfoList: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            message: "请选择任务配置",
            trigger: "change",
          },
        ],
      },
      factoryList: [], //工厂列表
      taskTypeSearchKey: null,
      taskConfigNameSearchKey: null,
      taskConfigurationList: [], //任务配置列表
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false, //任务配置列表loading
      saveloading: false,
      workTree: null,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    canEdit() {
      if (this.row?.id) {
        return checkPermi(["taskMgmt:center:add"]);
      }
      return true;
    },
    taskTypeOptionsMap() {
      return this.dictToMap(this.dict.taskType);
    },
    taskNatureOptionsMap() {
      return this.dictToMap(this.dict.taskNature);
    },
  },
  async created() {
    // 工厂-车间-产线-工序-工位
    this.workTree = new WorkTree();
    await this.workTree.affterLoad();
    this.factoryList = this.workTree.getFactory();
  },
  methods: {
    handleClose() {
      this.form = {
        ownedFactory: null,
        actualExecuteStartTime: null,
        actualExecuteEndTime: null,
        taskConfigInfoList: [],
      };
      this.saveloading = false;
      this.taskTypeSearchKey = null;
      this.taskConfigNameSearchKey = null;
      this.taskConfigurationList = [];
      this.$refs.ruleForm.resetFields();
    },
    handleOpen() {
      // 默认获取第一个工厂
      const results = this.getOwnFirstLine();
      this.form.ownedFactory = results[0]?.factoryDeptCode || null;
    },
    handleSearch() {
      this.pager.pageNum = 1;
      this.getList();
    },
    // 获取任务配置列表
    getList() {
      if (!this.form.ownedFactory) {
        return;
      }
      this.tableLoading = true;
      const { pageNum, pageSize } = this.pager;
      const params = {
        query: {
          taskType: this.taskTypeSearchKey,
          ownedFactory: this.form.ownedFactory,
          status: "1", //启用状态的
          taskName: this.taskConfigNameSearchKey,
        },
        pageNum,
        pageSize,
      };
      getTaskConfigList(params)
        .then((res) => {
          this.taskConfigurationList = res.rows || [];
          this.pager.total = res.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.taskConfigurationList = [];
          this.pager.total = 0;
          this.tableLoading = false;
        });
    },
    handleSubmit() {
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          this.saveloading = true;
          const { ownedFactory, actualExecuteStartTime, actualExecuteEndTime } =
            this.form;

          const taskConfigInfoList = this.$refs.table.selection;
          if (!taskConfigInfoList?.length) {
            this.msgError("请选择任务配置！");
            this.saveloading = false;
            return;
          }

          const param = {
            id: this.row?.id || null,
            taskConfigInfoList: taskConfigInfoList.map((ele) => ({
              taskCode: ele.taskCode,
              ownedWorkshop: ele.ownedWorkshop,
              ownedProductionLine: ele.ownedProductionLine,
              operator: ele.operator,
              executiveAgency: ele.executiveAgency,
            })),
            ownedFactory,
            actualExecuteStartTime,
            actualExecuteEndTime,
            source: "manual",
          };

          // 校验
          const emtyitem = param.taskConfigInfoList.find((ele) => {
            if (ele.executiveAgency) {
              return false;
            }
            if (ele.ownedWorkshop && ele.ownedProductionLine && ele.operator) {
              return false;
            }
            return true;
          });
          if (emtyitem) {
            this.msgError("任务执行人未填写完整！");
            this.saveloading = false;
            return;
          }

          saveTask(param)
            .then((res) => {
              this.msgSuccess("保存成功！");
              this.$emit("refresh");
              this.dialogVisible = false;
            })
            .finally(() => {
              this.saveloading = false;
            });
        }
      });
    },
    // 获取车间下拉选项
    getWorkshopOptions(ownedFactory) {
      if (!ownedFactory) {
        return [];
      }
      const options = this.workTree.getWorkshop({
        factoryDeptCode: ownedFactory,
      });
      return options;
    },
    // 获取产线下拉选项
    getProductionLineOptions(ownedWorkshop) {
      if (!ownedWorkshop) {
        return [];
      }
      const options = this.workTree.getProductionLine({
        workshopCode: ownedWorkshop,
      });
      return options;
    },
    // 获取工位下拉选项
    getStationOptions(ownedProductionLine) {
      if (!ownedProductionLine) {
        return [];
      }
      const options = this.workTree.getWorkStation({
        lineCode: ownedProductionLine,
      });
      return options;
    },
    handleOperatorChange(row, key, value) {
      if (key == "executiveAgency") {
        value = value?.code;
      }
      const item = this.$refs.table.selection.find((ele) => ele.id == row.id);
      if (item) {
        item[key] = value;
      }
      // 更改车间，清空产线
      if (key == "ownedWorkshop") {
        row.ownedProductionLine = null;
        if (row.operatorType == "station") {
          row.operator = null;
        }
      }
      // 更改产线，清空工位
      if (key == "ownedProductionLine") {
        if (row.operatorType == "station") {
          row.operator = null;
        }
      }
    },
  },
  watch: {
    "form.ownedFactory": {
      handler(newVal) {
        if (newVal) {
          this.getList();
        } else {
          this.taskConfigurationList = [];
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.search-bar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.in-row {
  display: flex;
  justify-content: flex-start;
  gap: 8px;
  align-items: center;
  .el-form-item {
    margin-bottom: 0;
  }
}
.task-config-list {
  margin-bottom: 0;
}
.bottom-gap {
  margin-bottom: 20px;
}
.w200 {
  width: 200px;
}
.executive-agency {
  display: inline-block;
}
</style>
